package com.bestcem.xm.award.grpc.client;

import com.alibaba.fastjson.JSONObject;
import com.bestcem.bp.grpc.v1.base.Code;
import com.bestcem.bp.grpc.v1.base.Status;
import com.bestcem.bp.xm.user.grpc.v1.services.GetOrgByIdOrCodeRequest;
import com.bestcem.bp.xm.user.grpc.v1.services.GetOrgByIdOrCodeResponse;
import com.bestcem.bp.xm.user.grpc.v1.services.OrgServiceGrpc;
import com.bestcem.bp.xm.user.grpc.v1.services.UserServiceGrpc;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
import zhongyan.xm.base.v1.Base;

import java.util.Objects;

import static com.bestcem.xm.award.constant.Constants.BLANK;

/**
 * 倍市得 user 模块相关rpc接口客户端
 *
 * @author sh.pei <sh.pei@idiaoyan.com>
 * @version v1.0
 * @date 2021/8/23 17:47
 */
@Slf4j
@Service
public class AwardBaseUserGrpcService {

    @GrpcClient(GrpcClientNames.DS_USER)
    private OrgServiceGrpc.OrgServiceBlockingStub orgServiceBlockingStub;

    @GrpcClient(GrpcClientNames.DS_USER)
    private UserServiceGrpc.UserServiceBlockingStub userServiceBlockingStub;


    /**
     * 获取钱包id
     *
     * @param orgId
     * @return
     */
    public ServiceResult<String> getWalletId(String orgId) {
        GetOrgByIdOrCodeRequest.Builder builder = GetOrgByIdOrCodeRequest.newBuilder();
        builder.setId(orgId);
        try {
            GetOrgByIdOrCodeResponse response = orgServiceBlockingStub.getOrgByIdOrCode(builder.buildPartial());
            if (Code.ERROR.equals(response.getStatus().getCode())) {
                return ServiceResult.fail(response.getStatus().getMessage());
            }
            if (response.getStatus().getCodeValue() != Code.OK_VALUE) {
                log.error("[award] 查询钱包id失败{},{}", orgId, response);
                return ServiceResult.fail(response.getStatus().getMessage());
            }
            return ServiceResult.success(response.getOrg().getWalletId());
        } catch (Exception e) {
            log.error("[award] USER getOrganization {} Error; ErrorMsg: {}", orgId, e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取单个Organization
     *
     * @param request 请求数据
     * @return Organization信息
     */
    public GetOrgByIdOrCodeResponse getOrganization(GetOrgByIdOrCodeRequest request) {
        try {
            return orgServiceBlockingStub.getOrgByIdOrCode(request);
        } catch (Exception e) {
            log.error("[award] base_user.proto/GetOrganization调用失败, request:{}; ErrorMsg: {}", request, e.getMessage(), e);
            return GetOrgByIdOrCodeResponse.newBuilder().setStatus(error()).build();
        }
    }

    /**
     * 中奖短信发送 获取系统名称
     *
     * @param orgId 组织id
     * @return 系统名称
     */
    public String getSystemName(String orgId) {
        String systemName = BLANK;
        GetOrgByIdOrCodeResponse organizationResponse = getOrganization(GetOrgByIdOrCodeRequest.newBuilder().setId(orgId).build());
        if (Base.Code.OK_VALUE != organizationResponse.getStatus().getCodeValue()) {
            log.error("[award] sendSms getOrganization,获取组织信息失败,orgId={}; ErrorMsg: {}", orgId, organizationResponse.getStatus().getMessage());
        } else {
            // 组织信息
            String skin = null;
            try {
                skin = organizationResponse.getOrg().getSkin();
                if (log.isInfoEnabled()) {
                    log.info("[award] sendSms 组织皮肤信息: skin={}, orgId={}", skin, orgId);
                }
                JSONObject jsonObject = JSONObject.parseObject(skin);
                // 自定义的系统名称是否使用
                boolean status = Boolean.parseBoolean(jsonObject.getString("status"));
                if (status) {
                    systemName = Objects.isNull(jsonObject.getString("name")) ? BLANK : jsonObject.getString("name");
                }
            } catch (Exception e) {
                log.error("[award] sendSms 获取组织皮肤信息获取系统名称失败: jsonData={}, orgId={} ", skin, orgId, e);
                systemName = BLANK;
            }
        }
        return systemName;
    }

    /**
     * 构造错误状态
     *
     * @return 错误信息
     */
    private Status error() {
        Status.Builder status = Status.newBuilder();
        status.setMessage("user-grpc服务调用失败");
        status.setCode(Code.ERROR);
        return status.build();
    }
}
